package com.maodou.android.viewmodel.main

import androidx.lifecycle.viewModelScope
import com.maodou.android.data.remote.UserRepository
import com.maodou.core.base.BaseViewModel
import com.maodou.core.datastore.db.AccountStore
import com.maodou.core.manager.GlobalStateManager
import com.maodou.core.network.NetworkError
import com.maodou.core.network.handleResult
import com.maodou.core.network.isUnauthorized
import com.maodou.core.utils.Logger
import dagger.hilt.android.lifecycle.HiltViewModel
import javax.inject.Inject
import kotlinx.coroutines.launch

data class MainUiState(
    val userText: String = "-",
    val listText: String = "-",
    val isLoading: Boolean = false,
    val tabs: List<String> = emptyList()
)

sealed interface MainUiEvent {
    data class ShowMessage(val message: String) : MainUiEvent
}


@HiltViewModel
class MainViewModel @Inject constructor(
    private val globalStateManager: GlobalStateManager,
    private val repo: UserRepository,
    private val accountStore: AccountStore
) : BaseViewModel<MainUiState, MainUiEvent>() {

    override fun createInitialState(): MainUiState {
        return MainUiState()
    }

    override fun setLoading(isLoading: Boolean) {
        updateUiState { it.copy(isLoading = isLoading) }
    }

    override fun handleError(error: Throwable) {
        val msg = when (error) {
            is NetworkError -> {
                if (error.isUnauthorized()) {
                    "鉴权失效，请重新登录"
                } else {
                    "请求失败: $error"
                }
            }
            else -> "未知错误: ${error.message}"
        }
        Logger.d("页面错误：$msg")
        setLoading(false)
    }

    private fun emitMessage(msg: String) {
        emitUiEvent(MainUiEvent.ShowMessage(msg))
    }

    private fun onFailure(err: NetworkError) {
        err.cause?.let { handleError(it) }
    }

    fun loadUserDirect(id: Long = 1) {
        setLoading(true)
        viewModelScope.launch {
            repo.loadUserDirect(id).handleResult(
                onSuccess = { user ->
                    updateUiState {
                        it.copy(
                            userText = "用户: ${user.name} (${user.email})",
                            isLoading = false
                        )
                    }
                },
                onError = { error ->
                    onFailure(error)
                }
            )
        }
    }

    fun loadUserEnvelope(id: Long = 1) {
        setLoading(true)
        viewModelScope.launch {
            repo.loadUserEnvelope(id).handleResult(
                onSuccess = { user ->
                    updateUiState {
                        it.copy(
                            userText = "用户: ${user.name} (${user.email})",
                            isLoading = false
                        )
                    }
                },
                onError = { error ->
                    onFailure(error)
                }
            )
        }
    }

    fun loadUserWithAuthRetry(id: Long = 1) {
        setLoading(true)
        viewModelScope.launch {
            repo.loadUserWithAuthRetry(id) { 
                // 这里应该实现 token 刷新逻辑
                // 暂时返回 false 表示刷新失败
                false
            }.handleResult(
                onSuccess = { user ->
                    updateUiState {
                        it.copy(
                            userText = "用户: ${user.name} (${user.email})",
                            isLoading = false
                        )
                    }
                },
                onError = { error ->
                    onFailure(error)
                }
            )
        }
    }

    fun loadUsersPage(page: Int = 1, pageSize: Int = 10) {
        setLoading(true)
        viewModelScope.launch {
            repo.loadUsersPage(page, pageSize).handleResult(
                onSuccess = { pageData ->
                    updateUiState {
                        it.copy(
                            listText = "用户列表: 第${pageData.current}页，共${pageData.total}条，当前${pageData.records.size}个用户",
                            isLoading = false
                        )
                    }
                },
                onError = { error ->
                    onFailure(error)
                }
            )
        }
    }

    fun loadUserRecords(page: Int = 1, pageSize: Int = 10) {
        setLoading(true)
        viewModelScope.launch {
            repo.loadUserRecords(page, pageSize).handleResult(
                onSuccess = { records ->
                    updateUiState {
                        it.copy(
                            listText = "用户记录: 总计 ${records.size} 条记录",
                            isLoading = false
                        )
                    }
                },
                onError = { error ->
                    onFailure(error)
                }
            )
        }
    }

    fun createUser(name: String = "Alice", email: String = "alice@example.com", username: String = "alice") {
        setLoading(true)
        viewModelScope.launch {
            repo.createUser(name, email, username).handleResult(
                onSuccess = {
                    emitMessage("用户创建成功: $name")
                    setLoading(false)
                },
                onError = { error ->
                    onFailure(error)
                }
            )
        }
    }

    fun logout(){
        viewModelScope.launch {
            globalStateManager.logout()
        }
    }

    fun loadAccountCategories() {
        // 模拟异步拉取，当前直接更新
        updateUiState { it.copy(tabs = listOf("个人号", "企业号")) }
    }
}
